package com.zxkj.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/5.
 */
//@Configuration
//@EnableTransactionManagement
//@EnableJpaRepositories(
//        entityManagerFactoryRef="entityManagerFactoryMssql",
//        transactionManagerRef="transactionManagerMssql",
//        basePackages= { "com.zxkj.mssql.repository" }) //设置Repository所在位置
public class MssqlConfig {

    @Autowired
    @Qualifier("mssqlDataSource")
    private DataSource mssqlDataSource;


    @Bean(name = "entityManagerPrimary")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryMssql(builder).getObject().createEntityManager();
    }

    @Bean(name = "entityManagerFactoryMssql")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryMssql (EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(mssqlDataSource)
                .properties(getVendorProperties(mssqlDataSource))
                .packages("com.zxkj.mssql.entity") //设置实体类所在位置
                .persistenceUnit("mssqlPersistenceUnit")
                .build();
    }

    @Autowired
    private JpaProperties jpaProperties;
    private Map<String, String> getVendorProperties(DataSource dataSource) {
        return jpaProperties.getHibernateProperties(dataSource);
    }

    @Bean(name = "transactionManagerMssql")
    public PlatformTransactionManager transactionManagerMssql(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryMssql(builder).getObject());
    }
}
